<template>
  <div class="article-editor">
    <!-- 编辑器头部 -->
    <div class="editor-header">
      <h2>新建文章</h2>
      <div class="action-buttons">
        <button @click="saveDraft" class="btn save-draft-btn">保存草稿</button>
        <button @click="publish" class="btn primary">立即发布</button>
      </div>
    </div>

    <!-- 主编辑区 -->
    <div class="editor-main">
      <!-- 左侧表单 -->
      <div class="form-section">
        <!-- 文章标题 -->
        <div class="form-item">
          <label>标题：</label>
          <input
              type="text"
              v-model="article.title"
              placeholder="请输入标题"
              class="title-input"
          >
        </div>
        <!-- 文章类型 -->
        <div class="form-item">
          <label>文章类型：</label>
          <select v-model="article.article_type" class="article_type-select" @change="resetImages">
            <option
                v-for="item in articleTypes"
                :key="item.value"
                :value="item.value"
                :selected="item.value === article.article_type"
            >
              {{ item.label }}
            </option>
          </select>
        </div>
        <!-- 文章分类 -->
        <div class="form-item">
          <label>分类：</label>
          <select v-model="article.category" class="category-select">
            <option
                v-for="category in categories"
                :key="category.id"
                :value="category.id"
                :selected="category.id === article.category"
            >
              {{ category.name }}
            </option>
          </select>
        </div>
        <!-- 文章标签 -->
        <div class="form-item">
          <label>标签：</label>
          <div class="tag-group">
            <div class="tag-input-wrapper">
              <input
                  type="text"
                  v-model="tagInput"
                  placeholder="输入标签，用逗号分隔"
                  @blur="updateTags"
                  @keyup.enter="updateTags"
              />
            </div>
          </div>
        </div>
        <!--是否允许评论-->
        <div class="form-item">
          <label>是否开启评论：</label>
          <label class="switch">
            <input type="checkbox" v-model="article.is_commentable">
            <span class="slider round"></span>
          </label>
        </div>
        <!-- 封面图 -->
        <div class="form-item" v-if="article.article_type!== 'no_image'">
          <label>封面图：</label>
          <input
              type="file"
              :name="article.article_type==='single'? 'image' : 'images'"
              @change="handleImageUpload"
              accept="image/*"
              multiple
              class="cover-input"
          >
          <div class="image-preview-group">
            <!-- 单图预览 -->
            <div v-if="article.image && !article.images.length" class="image-preview-wrapper">
              <img :src="article.image" class="cover-preview" @click="removeCoverImage">
            </div>
            <!-- 多图预览 -->
            <div v-else-if="article.images && article.images.length" class="image-grid">
              <div v-for="(img, index) in article.images"
                   :key="img.id || index"
                   class="image-preview-wrapper">
                <img :src="img.image" class="cover-preview" @click="removeImage(img, index)"/>
              </div>
            </div>
            <!-- 无图预览 -->
            <div v-else class="image-preview-wrapper">
              <p class="cover-preview">暂无封面图</p>
            </div>
          </div>
        </div>
        <!-- 文章摘要 -->
        <div class="form-item">
          <label>摘要：</label>
          <textarea
              v-model="article.excerpt"
              placeholder="文章摘要"
              class="summary-input"
          ></textarea>
        </div>
      </div>

      <!-- 右侧内容编辑器 -->
      <div class="content-section">
        <label>内容：</label>
        <div ref="editorRef" class="content-editor"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import E from 'wangeditor';

const editor = shallowRef(null)

const route = useRoute()
const router = useRouter()
const articleTypes = ref([
  {value: 'no_image', label: '无图'},
  {value: 'single', label: '单图'},
  {value: 'multi', label: '多图'}
])
const tags = ref([])

const tagInput = ref("");
// 修改标签解析方法
const parseTags = (tagString) => {
  // 增加全角逗号处理，兼容中英文输入
  return [...new Set(
      tagString.split(/[，,]/) // 同时匹配中文逗号和英文逗号
          .map(tag => tag.trim())
          .filter(tag => tag !== "")
  )]
}

const categories = ref([])
const getCategories = () => {
  axios.get(`/api/cms/categories/get_category_info`, {params: {pk:'2'}}).then(res => {
    categories.value = res.data;
  }).catch(error => {
    console.error('获取分类失败:', error)
  })
}

const article = reactive({
  title: '',
  article_type: 'no_image',
  category: null,
  tags: [],
  image: '',
  images: [],
  excerpt: '',
  content: '',
  is_commentable: true,
  status: 'draft',
})

// 更新标签处理方法
// 修改后的updateTags方法
const updateTags = () => {
  try {
    const tagNames = parseTags(tagInput.value)
    article.tags = tagNames.map(input => {
      // 优先匹配数字ID
      if (!isNaN(input)) {
        const idMatch = tags.value.find(t => t.id == input)
        if (idMatch) return idMatch
      }

      // 其次匹配名称
      const nameMatch = tags.value.find(t => t.name === input)
      return nameMatch || {name: input}
    })
  } catch (e) {
    console.error('标签处理异常:', e)
    article.tags = []
  }
}

const resetImages = () => {
  if (article.article_type === 'no_image') {
    article.image = '';
    article.images = [];
  } else if (article.article_type === 'single') {
    if (article.images.length > 0) {
      article.image = article.images[0].image;
      article.images = [];
    }
  }
}

const handleImageUpload = (e) => {
  const files = Array.from(e.target.files)
  if (!files.length) return

  files.forEach((file, index) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)

    reader.onload = (e) => { // 图片加载完成
      if (article.article_type === 'single') {
        article.image = e.target.result
        article.images = []
      } else if (article.article_type === 'multi') {
        article.images.push({
          image: e.target.result,
          order: article.images.length
        })
      }
    }
  })
}

const removeCoverImage = () => {
  article.image = '';
}

const removeImage = (img, index) => {
  article.images.splice(index, 1);
}

const saveArticle = async (isPublish = false) => {
  try {
    article.status = isPublish ? 'pending' : 'draft'
    if (editor.value) {
      article.content = editor.value.txt.html()
    }

    // 数据校验
    if (!article.title.trim()) {
      alert('标题不能为空')
      return
    }
    if (!article.content.trim()) {
      alert('内容不能为空')
      return
    }
    if (!article.category) {
      alert('请选择分类')
      return
    }
    // 创建FormData对象
    const formData = new FormData()

    // 处理图片上传
    if (article.article_type === 'single') {
      // 保留原有图片逻辑
      if (typeof article.image === 'string') {
        if (article.image.startsWith('/media')) {
          formData.append('image', article.image); // 传递原图路径
        } else if (article.image.startsWith('data:')) {
          const blob = dataURLtoBlob(article.image);
          formData.append('image', blob, 'cover.jpg');
        }
      }
    } else if (article.article_type === 'multi') {
      // 保留原有图片逻辑
      article.images.forEach((img) => {
        if (img.id && !img.image.startsWith('data:')) { // 原有图片
          formData.append('existing_images', img.id);
        } else { // 新图片
          // 增加dataURL格式校验
          if (img.image.startsWith('data:')) {
            const blob = dataURLtoBlob(img.image);
            formData.append('images', blob, `image-${Date.now()}.jpg`);
          }
        }
      });
    }

    // 添加文本字段
    formData.append('title', article.title.trim());
    formData.append('excerpt', article.excerpt.trim());
    formData.append('content', article.content);
    formData.append('article_type', article.article_type);
    formData.append('category', article.category);
    formData.append('status', isPublish ? 'pending' : 'draft');
    formData.append('is_commentable', article.is_commentable);
    formData.append('id', route.params.id);

    // 添加标签（兼容现有标签和新建标签）
    article.tags.forEach(tag => {
      const formKey = 'tags[]' // 使用数组语法
      const formValue = tag.id ? tag.id : tag.name
      formData.append(formKey, formValue)
    })
    console.log(formData.getAll('images'))
    const response = await axios.post(
        `/api/cms/articles/create_article/`,
        formData,
        {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
          requiredAuth: true
        }
    );
    const successMsg = isPublish ? '✅ 文章提交发布成功' : '💾 草稿保存成功';
    alert(successMsg);

    // 添加成功后的跳转逻辑（可选）
    setTimeout(() => {
      router.push({name: 'list-articles'});
    }, 1500);
  } catch (error) {
    console.error('操作失败:', error);
    const errorMsg = error.response?.data?.message || '操作失败，请检查网络连接';
    alert(`❌ ${errorMsg}`);
  }
}

const saveDraft = () => saveArticle(false);
const publish = () => saveArticle(true);

const dataURLtoBlob = (dataUrl) => {
  if (!dataUrl.startsWith('data:')) {
    alert('⚠️ 图片格式错误，请重新选择');
    return new Blob();
  }

  const arr = dataUrl.split(',');
  const mimeMatch = arr[0].match(/:(.*?);/);
  if (!mimeMatch) {
    console.error('Invalid MIME type format:', dataUrl)
    return new Blob()
  }

  const mime = mimeMatch[1];
  const bstr = atob(arr[1]);
  const u8arr = new Uint8Array(bstr.length);

  for (let i = 0; i < bstr.length; i++) {
    u8arr[i] = bstr.charCodeAt(i);
  }

  return new Blob([u8arr], {type: mime});
};

onMounted(() => {
  editor.value = new E('.content-editor');

  editor.value.config.height = 486;
  editor.value.config.placeholder = '请输入内容...';
  editor.value.config.onchangeTimeout = 500;
  editor.value.config.zIndex = 100;

  editor.value.config.onchange = (html) => {
    article.content = html;
  };

  editor.value.create();
  getCategories();
});

onBeforeUnmount(() => {
  if (editor.value) {
    try {
      editor.value.txt.clear()
      editor.value.destroy()
    } catch (e) {
      console.error('编辑器销毁异常:', e)
    } finally {
      editor.value = null
    }
  }
})
</script>

<style scoped>
@import '@/assets/accounts/css/personalcms.css';
</style>
